package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: thoughtworker
 * Date: 10/14/13
 * Time: 1:47 PM
 * To change this template use File | Settings | File Templates.
 */
public class LoginMenu implements MenuOptions{
    private CurrentUser currentUser;
    private Map<String, UserAccount> userAccounts;
    private PrintStream printStream;
    private BufferedReader reader;

    private Collection<String> userNameInstructions = Arrays.asList("Enter username:");
    private Collection<String> passwordInstructions = Arrays.asList("Enter password:");


    public LoginMenu(PrintStream printStream, BufferedReader reader, Map<String, UserAccount> userAccounts, CurrentUser currentUser){
        this.printStream = printStream;
        this.reader = reader;
        this.userAccounts = userAccounts;
        this.currentUser = currentUser;
    }

    @Override
    public void execute() throws IOException {

        if (currentUser.getUser() == null) {
            Menu menu = new Menu(printStream, reader, userNameInstructions);
            String username = menu.promptUserInput();
            menu = new Menu(printStream, reader, passwordInstructions);
            String password = menu.promptUserInput();
            if (userAccounts.containsKey(username) && userAccounts.get(username).checkPassword(password)) {
                userAccounts.get(username).login();
                currentUser.setUser(userAccounts.get(username));
                printStream.println("You have successfully logged in.");
            }
            else {
                printStream.println("Sorry, incorrect username or password.");
            }

        } else {
            printStream.println("You are already logged in.");
        }

    }
}
